SUIPatternLibrary.EngineView = (function($, _, app){
var

    $el = $("body"),
    $overlay = undefined,

    observable = {},
    engine = undefined,

    highlightedPattern = [],

    init = function(_engine){
        engine = _engine;
        addMouseInteraction();
    },

    highlightPattern = function(patternName){
        var pattern = engine.pattern;
        for(var i = 0, max = pattern.length; i < max; i++){
            if(pattern[i].name == patternName){
                var $patternElement = $(pattern[i].selector);
                if($overlay == undefined){
                    createOverlay($patternElement);
                }
                highlightedPattern.push(patternName);
                highlightedPattern = _.uniq(highlightedPattern);
                break;
            }
        }
    },

    createOverlay = function($element){
        if($element == null || $element == undefined || $element.length == 0) return;

        $overlay = app.TemplateManager.compileTemplate("overlay", {
            width : $element.width() + 10,
            height : $element.height() + 10,
            left : $element.offset().left - $el.offset().left - 5,
            top : $element.offset().top - 5
        });
        $el.append($overlay);
        $overlay.hover(function(){}, function(){
            $(observable).trigger("patternHover", undefined);
        });
        $overlay.click(function(){
            $(observable).trigger("patternClick", JSON.stringify(highlightedPattern));
        });
        $overlay.css("z-index", 1000);
    },

    unhighlightAll = function(){
        if($overlay == undefined) return;
        $overlay.remove();
        $overlay = undefined;
        highlightedPattern = [];
    },

    addMouseInteraction = function(){
        var pattern = engine.pattern;
        for(var i = 0, max = pattern.length; i < max; i++){
            if(pattern[i].selector)
                addPatternHoverEvent($(pattern[i].selector), pattern[i].name);
        }
    },

    addPatternHoverEvent = function($element, patternName){
        $element.hover(function(){
            $(observable).trigger("patternHover", patternName);
        });
    },

    getEngine = function(){
        return engine;
    }

    return {
        init : init,
        highlightPattern : highlightPattern,
        unhighlightAll : unhighlightAll,
        getEngine : getEngine,
        on : function(event, callback){
            $(observable).on(event, callback);
        }
    }

}(jQuery, _, SUIPatternLibrary));